#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Buynow'
from domain.linkman import linkman
import os

class linkman_dao:
    def __init__(self,save_local):
        self.linkman_dict = self.load_linkmans_bydisk(save_local)
        self.save_local = save_local


    def add_linkman(self,linkman):
        self.linkman_dict[linkman.name] = linkman

    def list_linkman(self):
        return self.linkman_dict

    def backup_linkman(self):
        self.save_linkmans_todisk(self.save_local,self.linkman_dict)



    def find_byname(self,name):
        return self.linkman_dict['name']

    def del_byname(self, name):
        if self.linkman_dict.__contains__(name):
            del self.linkman_dict[name]

    # 从文本文件加载
    def load_linkmans_bydisk(self,local):
        tmp_linkman_dict = {}
        tmp_linkman = None
        tmp_splits = None
        with open(file=local,mode='r') as f:
            for s in f:
                s = s.rstrip('\n')
                tmp_linkman = linkman()
                tmp_splits = s.split(' ')
                tmp_linkman.name = tmp_splits[0]
                tmp_linkman.phone = tmp_splits[1]
                tmp_linkman.address = tmp_splits[2]
                tmp_linkman_dict[tmp_linkman.name] = tmp_linkman
        return tmp_linkman_dict

    def save_linkmans_todisk(self,local,linkman_dict):
        with open(file=local,mode='w') as f:
            for (k,v) in linkman_dict.items():
                f.write(v.__str__()+'\n')

if __name__ == '__main__':
# test
    local = 'H:\\project\\pyProject\\phone_book\\resources\\data'
    dao = linkman_dao(local)
    d = dao.load_linkmans_bydisk(local)
    for (k,v) in d.items():
        print(k,v)
    d['zhao1'].phone = '110'
    dao.save_linkmans_todisk(local,d)